package artid.com.arttogo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import artid.com.arttogo.R;
import artid.com.arttogo.activity.ChatActivity;
import artid.com.arttogo.activity.MainActivity;
import artid.com.arttogo.adapter.PersonMessageAdapter;

/**
 *
 *
 * 项目名称：ArtworkArt   
 * 类名称：PersonMessage_Fragment   
 * 类描述：个人消息   
 * 创建人：耿卫斌   
 * 创建时间：2016-6-12 下午12:12:34   
 *
 */
public class PersonMessage_Fragment extends BaseFragment{
	private View v;
	private Context mContext;
	private PersonMessageAdapter adapter;
	private List<EMConversation> conversationList;
	private ListView mListview;
	private View noDataLL;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 1:
					if(conversationList!=null) {
						conversationList.clear();
					}
					conversationList.addAll(loadConversationsWithRecentChat());
					if (adapter == null && conversationList != null && conversationList.size() != 0) {
						adapter = new PersonMessageAdapter(mContext,conversationList);
						mListview.setAdapter(adapter);
					}
					if(conversationList != null && conversationList.size() != 0){
						noDataLL.setVisibility(View.GONE);
					}else{
						noDataLL.setVisibility(View.VISIBLE);
					}
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
					break;

				default:
					break;
			}
		};
	};
	@Override
	public View onCreateView(LayoutInflater inflater,
							 @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v=inflater.inflate(R.layout.fragment_personmessage, null);
		mContext=getActivity();
		initView();
		return v;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getData();
	}

	private void getData() {
		// TODO Auto-generated method stub
		//		ToastUtil.toast(mContext, AppUtil.getUser().getUid()+"：聊天记录已刷新");
		refreshHxMessage();
	}

	private void initView(){
		conversationList = new ArrayList<EMConversation>();
		EMClient.getInstance().chatManager().addMessageListener(msgListener);
		noDataLL=(View) v.findViewById(R.id.sysmess_blank);
		mListview=(ListView) v.findViewById(R.id.PersonMessageFragment_listView);
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
									long arg3) {
				// TODO Auto-generated method stub
				// 进入聊天页面
				ChatActivity.message=conversationList.get(position).getLastMessage();
				Intent intent = new Intent(mContext, ChatActivity.class);
				ChatActivity.message=conversationList.get(position).getLastMessage();
				MainActivity.friendAvatar=conversationList.get(position).getLastMessage().getStringAttribute("A_head", "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
				startActivity(intent);
			}
		});
	}


	/**
	 * 刷新环信会话列表
	 */
	public void refreshHxMessage() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(1);
			}
		}).start();
	}

	/**
	 * 获取所有会话
	 *
	 * @return +
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Map<String, EMConversation> conversations = EMClient.getInstance()
				.chatManager().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
		}

		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
					@Override
					public int compare(final Pair<Long, EMConversation> con1,
									   final Pair<Long, EMConversation> con2) {

						if (con1.first == con2.first) {
							return 0;
						} else if (con2.first > con1.first) {
							return 1;
						} else {
							return -1;
						}
					}

				});
	}


	/**
	 * 环信消息接收
	 */
	EMMessageListener msgListener = new EMMessageListener() {

		@Override
		public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 透传消息
			Log.d("log", "环信透传消息:" + list_EMMessage.toString());

		}
		@Override
		public void onMessageRead(List<EMMessage> list) {

		}

		@Override
		public void onMessageDelivered(List<EMMessage> list) {

		}

		@Override
		public void onMessageChanged(EMMessage arg0, Object arg1) {
			// TODO Auto-generated method stub
			// 消息状态变动
		}


		@Override
		public void onMessageReceived(List<EMMessage> list_EMMessage) {
			// TODO Auto-generated method stub
			// 收到消息
			Log.d("log", "环信消息:" + list_EMMessage.toString());
			refreshHxMessage();
		}
	};

	/**
	 * 每次切换Fragment刷新页面
	 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		// 每次切换fragment时调用的方法
		if (isVisibleToUser) {
			getData();
		}
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		adapter=null;
	}

}
